package com.naizhuai.network;

import com.naizhuai.network.Cookie.Cache.SetCookieCache;
import com.naizhuai.network.Cookie.PersistentCookieJar;
import com.naizhuai.network.Cookie.persistent.SpCookiePersistor;
import com.naizhuai.util.ConstantsParams;
import com.naizhuai.util.ConstantsPersonResources;

import android.content.Context;
import android.support.annotation.IntDef;

import java.io.File;
import java.io.IOException;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.net.URLDecoder;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.Interceptor;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;
import okhttp3.logging.HttpLoggingInterceptor;
import okio.Buffer;

/**
 * Created by lichenxi on 2017/5/16.
 */

public class ClientFactory {
    private static final int DISK_CACHE_SIZE = 50 * 1024 * 1024;
    private static final int TIME_OUT = 60;/*seconds*/
    private static volatile OkHttpClient INSTANCE;

    public static OkHttpClient getInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (ClientFactory.class) {
                if (INSTANCE == null) {
                    INSTANCE = createHttpClient(context,null);
                }
            }
        }
        return INSTANCE;
    }
    public static OkHttpClient getDownloadInstance(Context context) {
        if (INSTANCE == null) {
            synchronized (ClientFactory.class) {
                if (INSTANCE == null) {
                    INSTANCE = createDownloadHttpClient(context);
                }
            }
        }
        return INSTANCE;
    }


    public static OkHttpClient getInstance(Context context,String privateKey) {
//        if (INSTANCE == null) {
//            synchronized (ClientFactory.class) {
//                if (INSTANCE == null) {
//                    INSTANCE = createHttpClient(context,privateKey);
//                }
//            }
//        }
        return createHttpClient(context,privateKey);
    }




    private static OkHttpClient createHttpClient(Context context,String privateKey) {
        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        File cachefile = new File(context.getExternalCacheDir(), "http");
        Cache cache = new Cache(cachefile, DISK_CACHE_SIZE);

        PersistentCookieJar cookieJar = new PersistentCookieJar(new SetCookieCache(), new SpCookiePersistor(context));


        if(privateKey==null){
            privateKey=ConstantsParams.PRIVATE_KEY;
        }

        return okHttpClient
                .cache(cache)
//                .addInterceptor(loggingInterceptor)
//                .addInterceptor(EADER_INTERCEPTOR)
                .cookieJar(cookieJar)
//                .addInterceptor(CACHE_CONTROL_INTERCEPTOR)
                .addNetworkInterceptor(new CommonParamsInterceptor(context,privateKey))
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();
    }


    private static OkHttpClient createDownloadHttpClient(Context context) {
        OkHttpClient.Builder okHttpClient = new OkHttpClient.Builder();
        return okHttpClient
                .addInterceptor(EADER_INTERCEPTOR)
                .addNetworkInterceptor(new CommonParamsInterceptor(context,null))
//                .addInterceptor(CACHE_CONTROL_INTERCEPTOR)
                .connectTimeout(TIME_OUT, TimeUnit.SECONDS)
                .build();
    }

    private static Interceptor EADER_INTERCEPTOR = new Interceptor() {
        @Override
        public Response intercept(Chain chain) throws IOException {
            Request request = chain.request();
            Request.Builder requestBuilder = request.newBuilder();
            request = requestBuilder.post(RequestBody.create(MediaType.parse("application/x-www-form-urlencoded;charset=GBK"),
                    URLDecoder.decode(bodyToString(request.body()), "UTF-8")))
                    .build();
            return chain.proceed(request);
        }
    };

    private static String bodyToString(final RequestBody request) {
        try {
            final RequestBody copy = request;
            final Buffer buffer = new Buffer();
            if (copy != null)
                copy.writeTo(buffer);
            else
                return "";
            return buffer.readUtf8();
        } catch (final IOException e) {
            return "did not work";
        }
    }

//    static Interceptor CACHE_CONTROL_INTERCEPTOR=new Interceptor() {
//        @Override
//        public Response intercept(Chain chain) throws IOException {
//            Request request = chain.request();
//           if (!NetUtils.isNetworkAvailable(BaseApp.getContext())){
//                 request.newBuilder().cacheControl(CacheControl.FORCE_CACHE)
//                         .build();
//                 UiUtil.showToastSafely("当前网络不可用");
//
//           }
//
//            Response originalResponse=chain.proceed(request);
//            //pragma也是控制缓存的一个消息头属性 只是http1.0的遗留版本 也是做缓存的
//           if (NetUtils.isNetworkAvailable(BaseApp.getContext())){
//               //有网的情况
//               int maxAge=5;//缓存的时间
//               return originalResponse.newBuilder()
//                               .removeHeader("Pragma")
//                       .header("Cache-Control", "public, max-age=" + maxAge)
//                       .build();
//
//           }else{
//               //没网的情况
//               //only-if-cached只接收缓存的内容
//               int maxStale = 60 * 60 * 24 * 28;//tolerate 4-weeks stale
//               return originalResponse.newBuilder()
//                       .removeHeader("Prama")
//                       //从缓存中获取资源 接收已经过期的响应
//                       .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
//                       .build();
//
//           }
//        }
//    };
}

